from flask import Flask, render_template, request, jsonify, send_from_directory
from flask_cors import CORS
import os
from datetime import datetime

app = Flask(__name__)
CORS(app)

# 配置Jinja2避免与Vue语法冲突
app.jinja_env.variable_start_string = '[[['
app.jinja_env.variable_end_string = ']]]'

UPLOAD_FOLDER = 'static/uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
os.makedirs(UPLOAD_FOLDER, exist_ok=True)


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/api/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({'error': '未上传文件'}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': '空文件名'}), 400

    if file and allowed_file(file.filename):
        timestamp = datetime.now().strftime('%Y%m%d%H%M%S%f')
        ext = os.path.splitext(file.filename)[1]
        filename = f"{timestamp}{ext}"
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(filepath)

        upload_time = int(os.path.getmtime(filepath) * 1000)
        return jsonify({
            'status': 'success',
            'filename': filename,
            'url': f'/static/uploads/{filename}',
            'upload_time': upload_time
        }), 200

    return jsonify({'error': '无效文件类型'}), 400


@app.route('/api/images')
def get_images():
    images = []
    for filename in os.listdir(app.config['UPLOAD_FOLDER']):
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        if os.path.isfile(filepath) and allowed_file(filename):
            upload_time = int(os.path.getmtime(filepath) * 1000)
            images.append({
                'filename': filename,
                'url': f'/static/uploads/{filename}',
                'upload_time': upload_time
            })

    images.sort(key=lambda x: x['upload_time'], reverse=True)
    return jsonify(images)


@app.route('/static/uploads/<path:filename>')
def serve_uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)


if __name__ == '__main__':
    app.run(debug=True, port=80,host='0.0.0.0')